package thread;

/**
 * @author weim
 * @date 18-8-29
 */
public class MySynchronized {

    public static Object object = new Object();
    public static Object object2 = new Object();

    private static Integer index = 0;

    public static void main(String[] args) {

//        for(int i=0; i<100; i++) {
//
//            new Thread(() -> {
//
//                count(Thread.currentThread().getName());
//
//            }).start();
//
//        }

//        for(int i=0; i<100; i++) {
//
//            new Thread(() -> {
//
//                count2(Thread.currentThread().getName());
//
//            }).start();
//        }


        //死锁
        new Thread(() -> {

            count3(Thread.currentThread().getName());

        }).start();

        new Thread(() -> {

            count4(Thread.currentThread().getName());

        }).start();


    }

    private static synchronized void count(String name) {
        index++;
        System.out.println(name + "     " + index);
    }

    private static void count2(String name) {
        synchronized (object) {
            index++;
            System.out.println(name + "     " + index);
        }
    }

    private static void count3(String name) {
        synchronized (object) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            index++;
            System.out.println(name + "  count3   " + index);

            synchronized (object2) {
                System.out.println(name + " count3  2->  " + index);
            }
        }
    }

    private static void count4(String name) {
        synchronized (object2) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            index++;
            System.out.println(name + " count4    " + index);

            synchronized (object) {
                System.out.println(name + " count4  2->  " + index);
            }
        }
    }
}


